import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import createVitePlugins from './vite/plugins'

// https://vite.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd())

  return {
    base: env.VITE_APP_BASE,

    plugins: createVitePlugins(env, command),

    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '~': fileURLToPath(new URL('./', import.meta.url)),
      },
      extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'],
    },

    server: {
      host: '0.0.0.0',
      port: Number(env.VITE_APP_PORT),
      open: true,
      proxy: {
        [env.VITE_APP_API]: {
          changeOrigin: true,
          target: env.VITE_APP_API_PROXY,
          rewrite: (path) => path.replace(new RegExp('^' + env.VITE_APP_API), ''),
        },
      },
    },

    build: {
      outDir: 'dist',
      assetsDir: 'assets',
    },
  }
})
